package com.controller.system.businessShop;

import com.entity.system.*;
import com.service.system.agent.AgentService;
import com.service.system.businessShop.BusinessShopService;
import com.service.system.user.UserInfoService;
import com.service.system.user.UserService;
import com.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/businessShop")
public class BusinessShopController {

    @Autowired
    BusinessShopService businessShopService;

    @Autowired
    AgentService agentService;

    @Autowired
    UserInfoService userInfoService;

    /**
     * 查询商铺列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findBusinessShopList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findBusinessShopList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", request.getParameter("pageSize"));
        map.put("pageNum", request.getParameter("pageNum"));
        if (StringUtils.isNotEmpty(request.getParameter("state"))) {
            map.put("state", request.getParameter("state"));
        }
        if (StringUtils.isNotEmpty(request.getParameter("isPreferredBusiness"))) {
            map.put("isPreferredBusiness", request.getParameter("isPreferredBusiness"));
        }
        if (StringUtils.isNotEmpty(request.getParameter("phone"))) {
            map.put("phone", request.getParameter("phone"));
        }
        if (StringUtils.isNotEmpty(request.getParameter("startTime"))) {
            map.put("startTime", request.getParameter("startTime"));
        }
        if (StringUtils.isNotEmpty(request.getParameter("endTime"))) {
            map.put("endTime", request.getParameter("endTime"));
        }
        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Map<String, Object> map1 = (Map<String, Object>) session.getAttribute(Const.SESSION_allmenuList);
        Map<String, Object> map2 = new HashMap<>();
        AgentNew an = null;
        if (null == map1) {
            map2.put("code", Const.ERROR_CODE);
            map2.put("message", "查询失败");
            return map2;
        } else {
            //当前登录用户角色
            StaticRole sr = (StaticRole) map1.get("staticRole");
            if (sr != null && sr.getRoleCode().equals("VERSION_NEW_ROLE_AGENT")) {
                UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
                //代理商信息
                an = agentService.getAgentNewByUserId(user.getId());
                if (an == null) {
                    LogUtil.info("*************你不是代理商*******************");
                    map2.put("code", Const.ERROR_CODE);
                    map2.put("message", "查询失败");
                    return map2;
                }
            }
        }
        map.put("an", an);
        return businessShopService.findBusinessShopList(map);
    }

    /**
     * 店铺审核
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/auditBus", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> auditBus(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)) {
            map.put("code", Const.ERROR_CODE);
            map.put("message", "审核失败");
            return map;
        }
        String auditType = request.getParameter("auditType");
        if (StringUtils.isEmpty(auditType)) {
            map.put("code", Const.ERROR_CODE);
            map.put("message", "审核失败");
            return map;
        }
        String content = request.getParameter("content");
        if ("2".equals(auditType)) {
            if (StringUtils.isEmpty(content)) {
                map.put("code", Const.ERROR_CODE);
                map.put("message", "审核失败");
                return map;
            }
        }
        return businessShopService.auditBus(id, auditType, content);
    }

    /**
     * 查询商户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findMerchantsList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findMerchantsList(HttpServletRequest request) {
        String pageSize = request.getParameter("pageSize");
        String pageNum = request.getParameter("pageNum");
        String state = request.getParameter("state");
        String isPreferredBusiness = request.getParameter("isPreferredBusiness");
        String label = request.getParameter("label");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String phone = request.getParameter("phone");
        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Map<String, Object> map1 = (Map<String, Object>) session.getAttribute(Const.SESSION_allmenuList);
        Map<String, Object> map2 = new HashMap<>();
        AgentNew an = null;
        if (null == map1) {
            map2.put("code", Const.ERROR_CODE);
            map2.put("message", "查询失败");
            return map2;
        } else {
            //当前登录用户角色
            StaticRole sr = (StaticRole) map1.get("staticRole");
            if (sr != null && sr.getRoleCode().equals("VERSION_NEW_ROLE_AGENT")) {
                UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
                //代理商信息
                an = agentService.getAgentNewByUserId(user.getId());
                if (an == null) {
                    LogUtil.info("*************你不是代理商*******************");
                    map2.put("code", Const.ERROR_CODE);
                    map2.put("message", "查询失败");
                    return map2;
                }
            }
        }
        return businessShopService.findMerchantsList(pageSize, pageNum, state, isPreferredBusiness, label, an, startTime, endTime,phone);
    }

    /**
     * 消费金交易明细
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/consumerMoney", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> consumerMoney(HttpServletRequest request) {
        String pageSize = request.getParameter("pageSize");
        String pageNum = request.getParameter("pageNum");
        String phone = request.getParameter("phone");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Map<String, Object> map1 = (Map<String, Object>) session.getAttribute(Const.SESSION_allmenuList);
        Map<String, Object> map2 = new HashMap<>();
        AgentNew an = null;
        if (null == map1) {
            map2.put("code", Const.ERROR_CODE);
            map2.put("message", "查询失败");
            return map2;
        }

        Map<String, Object> map3 = new HashMap<>();

        //当前登录用户角色
        StaticRole sr = (StaticRole) map1.get("staticRole");
        if (sr != null && sr.getRoleCode().equals("VERSION_NEW_ROLE_AGENT")) {
            UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
            //代理商信息
            an = agentService.getAgentNewByUserId(user.getId());
            if (an == null) {
                LogUtil.info("*************你不是代理商*******************");
                map2.put("code", Const.ERROR_CODE);
                map2.put("message", "查询失败");
                return map2;
            } else {
                int level = an.getAgentLevel();
                if (level == 1) {
                    map3.put("level", "1");
                } else if (level == 2) {
                    map3.put("level", "2");
                } else if (level == 3) {
                    map3.put("level", "3");
                }
                String area = an.getCountyCode();
                String city = an.getCityCode();
                String province = an.getProvinceCode();
                map3.put("area", area);
                map3.put("city", city);
                map3.put("province", province);
            }
        }

        Long userId = 0L;
        //通过电话查询用户id
        if (StringUtils.isNotEmpty(phone)) {
            Map<String, Object> map = userInfoService.findUserByPhone(phone);
            String code = (String) map.get("code");
            if (Const.SUCCESS_CODE.equals(code)) {
                UserInfo ui = (UserInfo) map.get("user");
                userId = ui.getId();
            } else {
                map2.put("code", Const.ERROR_CODE);
                map2.put("message", "查询失败");
                return map2;
            }
        }

        //type 1:广告币充值订单 2创客合伙人订单  3:消费金充值订单  4:优惠买单订单'
        return businessShopService.findUserConsumerMoney(pageSize, pageNum, userId, startTime, endTime, 4, map3);
    }

    /**
     * 根据userId查询商铺信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findBusinessShopByUserId", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findBusinessShopByUserId(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        return businessShopService.findBusinessShopByUserId(userId);
    }

    /**
     * 商家审核
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/merchantsAudit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> merchantsAudit(HttpServletRequest request) {
        String id = request.getParameter("id"); //商家ID
        String type = request.getParameter("auditType"); //审核类型  1.通过  2.不通过
        String content = request.getParameter("content");
        return businessShopService.merchantsAudit(id, type, content);
    }

    /**
     * 查询分类列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findClassifyList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findClassifyList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", request.getParameter("pageSize"));
        map.put("pageNum", request.getParameter("pageNum"));
        return businessShopService.findClassifyList(map);
    }

    /**
     * 添加分类
     *
     * @param file
     * @param classify
     * @return
     */
    @RequestMapping(value = "/addClassify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> addClassify(MultipartFile file, Classify classify) {
        Map<String, Object> map = new HashMap<>();
        if (null != file) {
            ResourceBundle rs = ResourceBundle.getBundle("environment");
            String contentType = file.getContentType();
            String suffix = FileUtil.getContentTypeSuffix(contentType);
            String url = rs.getString("base.resource.url") + "/image/upload";
            LogUtil.info(url);
            try {
                Image image = FileUtil.uploadBytesAndPostBinImage(file.getBytes(), suffix, url);
                if (image != null) {
                    classify.setClassifyIcon(image.getUrl());
                } else {
                    map.put("code", Const.ERROR_CODE);
                    map.put("message", "添加失败");
                    return map;
                }
            } catch (IOException e) {
                e.printStackTrace();
                map.put("code", Const.ERROR_CODE);
                map.put("message", "添加失败");
                return map;
            }
        }
        return businessShopService.addClassify(classify);
    }

    /**
     * 修改分类
     *
     * @param file
     * @param classify
     * @return
     */
    @RequestMapping(value = "/updateClassify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> updateClassify(MultipartFile file, Classify classify) {
        Map<String, Object> map = new HashMap<>();
        if (null != file) {
            ResourceBundle rs = ResourceBundle.getBundle("environment");
            String contentType = file.getContentType();
            String suffix = FileUtil.getContentTypeSuffix(contentType);
            String url = rs.getString("base.resource.url") + "/image/upload";
            LogUtil.info(url);
            try {
                Image image = FileUtil.uploadBytesAndPostBinImage(file.getBytes(), suffix, url);
                if (image != null) {
                    classify.setClassifyIcon(image.getUrl());
                } else {
                    map.put("code", Const.ERROR_CODE);
                    map.put("message", "修改失败");
                    return map;
                }
            } catch (IOException e) {
                e.printStackTrace();
                map.put("code", Const.ERROR_CODE);
                map.put("message", "修改失败");
                return map;
            }
        }
        return businessShopService.updateClassify(classify);
    }

    /**
     * 删除分类
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/delClassify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> delClassify(HttpServletRequest request) {
        String id = request.getParameter("id");
        return businessShopService.delClassify(Integer.parseInt(id));
    }

    /**
     * 设置是否为优选商家
     * @param businessShopTemp
     * @return
     */
    @RequestMapping(value = "/updateIsPreferredBusiness",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> updateIsPreferredBusiness(BusinessShopTemp businessShopTemp){
        return businessShopService.updateIsPreferredBusiness(businessShopTemp);
    }
}
